package file;

import javax.swing.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo3 {
    public static void main(String[] args) throws IOException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要遍历的目录");
        String rootDirPath=scanner.next();
        System.out.println("请输入要查找的内容");
        String content=scanner.next();
        File rootDir=new File(rootDirPath);
        if(!rootDir.isDirectory()){
            System.out.println("输入路径非法");
            return;
        }
        List<File> list=new ArrayList<>();
        scanDirWithContent(rootDir,content,list);
        for(File f:list){
            System.out.println(f.getCanonicalPath());
        }
    }
    public static void scanDirWithContent(File rootDir,String content,List<File> list){
        File[] files=rootDir.listFiles();
        if(files==null){
            return;
        }
        for(File f:files){
            if(f.isFile()){
                if(isContentExists(f,content)){
                    list.add(f);
                }
            }else if(f.isDirectory()){
                scanDirWithContent(f,content,list);
            }
        }
    }
    public static boolean isContentExists(File f,String content){
        StringBuilder sb=new StringBuilder();
        try(Reader render=new FileReader(f)) {
            while (true){
                int c=render.read();
                if(c==-1){
                    break;
                }
                sb.append((char)c);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return sb.indexOf(content)!=1;
    }
}
